<template>
  <a-drawer
    width="100%"
    :destroyOnClose="true"
    placement="right"
    :closable="false"
    :visible="visible"
    :bodyStyle="{ padding: '0px' }"
    @cancel="cancel"
  >
    <div
      style="display: flex; align-items: flex-start; justify-content: center"
    >
      <div class="tab-add title" style="cursor: pointer">
        <label class="text-bold">
          <a-tooltip title="关闭">
            <a-icon
              @click="cancel"
              type="arrow-left"
              style="cursor: pointer"
            ></a-icon>
          </a-tooltip>
          正在编辑表单:</label
        >

        <a-tooltip :title="title">
          <span class="">{{ title }}</span>
        </a-tooltip>
      </div>

      <div style="width: 100%">
        <a-tabs v-model="curTabKey" @tabClick="tabClick">
          <a-tab-pane key="1" tab="编辑字段"> </a-tab-pane>
          <a-tab-pane key="2" tab="表单设置"> </a-tab-pane>
          <a-tab-pane key="3" tab="扩展功能"> </a-tab-pane>
          <template slot="tabBarExtraContent">
            <a-tooltip title="关闭">
              <a
                @click="cancel"
                style="color: #ff4d4f; padding-right: 10px; font-size: 18px"
              >
                <a-icon type="close" />
                <span>关闭</span>
              </a>
            </a-tooltip>
          </template>
        </a-tabs>
      </div>
    </div>
    <div v-show="curTabKey == '1'">
      <a-spin :spinning="spinning">
        <k-form-design
          ref="kfd"
          toolbarsTop
          :destroyOnClose="true"
          :showToolbarsText="true"
          :worksheet="{
            zeroCodeId: zeroCodeId,
          }"
          :zeroCodeId="zeroCodeId"
          :showHead="false"
          :toolbars="design.toolbars"
        >
          <template slot="left-action">
            <a-divider type="vertical" />
            <a-tooltip title="批量修改别名" @click="alias.visible = true">
              <a>
                <a-icon type="edit" />
                <span>别名</span>
              </a>
            </a-tooltip>

            <a-divider type="vertical" />
            <a-tooltip title="回收站" @click="recycle.visible = true">
              <a>
                <a-icon type="delete" />
                <span>回收站</span>
              </a>
            </a-tooltip>
            <a-divider type="vertical" />
            <a-tooltip title="发布" @click="designerPublic()">
              <a>
                <a-icon type="cloud-upload" />
                <span>发布</span>
              </a>
            </a-tooltip>
          </template>
        </k-form-design>
      </a-spin>
    </div>
    <div v-if="curTabKey == '2'">
      <setting-index
        :options="setting.options"
        :columns="setting.columns"
        :zeroCodeId="zeroCodeId"
        :settingkey="curSettingKey"
        :menuId="menuId"
      >
      </setting-index>
    </div>

    <alias-setting
      v-if="alias.visible"
      :table="alias.table"
      :zeroCodeId="zeroCodeId"
      :visible.sync="alias.visible"
      @save="aliasSave"
      title="别名设置"
    ></alias-setting>

    <recycle-setting
      v-if="recycle.visible"
      :visible.sync="recycle.visible"
      :zeroCodeId="zeroCodeId"
      @save="designerPublic"
      title="字段回收站"
    ></recycle-setting>
  </a-drawer>
</template>

<script>
import { mapMutations, mapGetters } from "vuex";
import {
  findById,
  editPublic,
  tableField,
  tableRename,
} from "@/services/system/zerocode/worksheet/designer";
import jsonFormat from "@/pages/system/zerocode/worksheet/components/packages/components/KFormDesign/config/jsonFormat";
import settingIndex from "./setting/index.vue";
import aliasSetting from "./alias";
import recycleSetting from "./recycle";
export default {
  name: "businessdatadesigner",
  data() {
    return {
      curTabKey: this.tabkey,
      curSettingKey: this.settingkey,
      design: {
        toolbars: [
          "preview",
          "importJson",
          "exportJson",
          "exportCode",
          "undo",
          "redo",
          "reset",
        ],
      },

      form: {
        zeroCodeId: this.zeroCodeId,
        name: "",
      },
      spinning: false,

      setting: {
        visible: false,
        type: "",
        options: {},
        columns: [],
      },

      alias: {
        data: [],
        table: "",
        visible: false,
      }, //字段别名

      recycle: {
        visible: false,
      },
    };
  },
  computed: {
    ...mapGetters("account", ["zeroCode"]),
  },
  components: {
    settingIndex,
    aliasSetting,
    recycleSetting,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    menuId: String,
    zeroCodeId: String,
    title: {
      type: String,
    },

    tabkey: {
      type: String,
      default: "1",
    },

    settingkey: {
      type: String,
      default: "1",
    },
  },
  mounted() {
    this.find();
  },
  methods: {
    ...mapMutations("account", ["setZeroCode"]),
    /**
     * 选项卡切换
     */
    tabClick() {
      this.setting.columns = this.$refs.kfd.getFieldSchema();
      if (this.curTabKey == "1") {
      }
      if (this.curTabKey == "2") {
      }
    },
    /**
     * 取消
     */
    cancel() {
      this.$emit("designerPublic");
      this.$emit("close");
    },

    /**
     * 发布表单设计
     */
    async designerPublic() {
      let that = this;
      //重新赋值
      var json = that.$refs.kfd.getValue();
      let fieldSchema = that.$refs.kfd.getFieldSchema();
      if (this.alias.data) {
        fieldSchema.forEach((f) => {
          var aliasFind = that.$utils.find(
            this.alias.data,
            (item) => item.key == f.key
          );
          f.modelBefore = aliasFind ? aliasFind.model : f.model;
        });
      }
      let param = {
        zeroCodeId: that.form.zeroCodeId,
        publicJson: JSON.stringify(json),
        columnJson: JSON.stringify(fieldSchema),
      };
      that.$loading.show({ text: "发布中,请稍等..." });

      let result = {
        code: 200,
      };

      //创建表字段
      result = await tableField({
        zeroCodeId: that.form.zeroCodeId,
        columns: JSON.stringify(fieldSchema),
      });
      if (result.code === that.eipResultCode.success) {
        that.alias.data = that.$utils.clone(fieldSchema, true);
        editPublic(param).then(function (result) {
          that.$loading.hide();
          if (result.code === that.eipResultCode.success) {
            that.alias.visible = false;
            that.designerPublicOk(param);
            that.$message.success(result.msg);
          } else {
            that.$message.error(result.msg);
          }
        });
      } else {
        that.$loading.hide();
        that.$message.error(result.msg);
      }
    },

    /**
     * 重置表单
     * @param {} form
     */
    designerPublicOk(form) {
      var systemZeroCodeData = this.zeroCode.filter(
        (f) => f.zeroCodeId == form.zeroCodeId
      );
      if (systemZeroCodeData && systemZeroCodeData.length > 0) {
        systemZeroCodeData[0].columnJson = form.columnJson;
        systemZeroCodeData[0].publicJson = form.publicJson;
        this.setZeroCode(this.zeroCode);
      }
    },

    /**
     * 根据Id查找
     */
    find() {
      let that = this;
      that.spinning = true;
      findById(this.zeroCodeId).then(function (result) {
        let form = result.data;
        that.form.name = form.name;
        that.form.zeroCodeId = that.zeroCodeId;
        that.setting.options = that.$utils.merge(
          that.$utils.clone(that.eipZeroCodeFormSetting, true),
          that.$utils.toStringJSON(result.data.settingJson)
        );

        if (form.publicJson) {
          that.$refs.kfd.handleSetData(JSON.parse(form.publicJson));
        } else {
          let def = JSON.parse(jsonFormat);
          that.$refs.kfd.handleSetData(def);
        }
        if (form.columnJson) {
          var columnJson = JSON.parse(form.columnJson);
          that.alias.data = that.$utils.clone(columnJson, true);
        }
        that.alias.table = form.tableName;
        that.spinning = false;
        that.eipFormDesigner.kfd = that.$refs.kfd;
      });
    },

    /**
     * 保存别名
     * @param data
     */
    async aliasSave(table) {
      //处理表别名
      var result = {
        code: this.eipResultCode.success,
      };
      if (this.alias.table != table) {
        this.$loading.show({ text: "别名保存中,请稍等..." });
        //创建表字段
        var result = await tableRename({
          zeroCodeId: this.form.zeroCodeId,
          tableName: table,
        });
        if (result.code !== this.eipResultCode.success) {
          this.$loading.hide();
          this.$message.error(result.msg);
        } else {
          this.alias.table = table;
        }
      }
      if (result.code == this.eipResultCode.success) {
        this.designerPublic();
      }
    },
    /**
     * 所有组件
     */
    setFieldSchema(columns) {
      let that = this;
      const traverse = (array) => {
        array.forEach((element) => {
          if (["grid", "tabs", "collapse"].includes(element.type)) {
            element.columns.forEach((item) => {
              traverse(item.list);
            });
          } else if (element.type === "card") {
            // 卡片布局
            traverse(element.list);
          } else if (element.type === "table") {
            // 表格布局
            element.trs.forEach((item) => {
              item.tds.forEach((val) => {
                traverse(val.list);
              });
            });
          } else {
            var find = that.$utils.find(columns, (f) => f.key == element.key);
            if (find) {
              element.model = find.model;
            }
          }
        });
      };
      var list = this.$refs.kfd.getValue().list;
      traverse(list);
      return list;
    },
  },
};
</script>
<style lang="less" scoped>
.tab-add {
  width: 60%;
  line-height: 24px;
  padding: 12px 10px 7px 10px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}
.title {
  font-size: 16px;
}
/deep/ .eip-form-designer-container {
  height: calc(100vh - 48px) !important;
}
/deep/ .ant-tabs-bar {
  margin: 0 !important;
}
</style>
